package com.quanjiaolian.userinfo.servlet;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.ResourceBundle;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.log4j.Logger;

import com.quanjiaolian.bean.InsInfo;
import com.quanjiaolian.bean.UserInfo;
import com.quanjiaolian.tools.ResponseToJson;
import com.quanjiaolian.tools.Utils;
import com.quanjiaolian.userinfo.service.UserInfoService;
import com.quanjiaolian.userinfo.serviceimpl.UserInfoServiceImpl;

/**
 * 
 * @author Herson_Li
 *
 */
@SuppressWarnings("serial")
public class UserInfoMain extends HttpServlet {
	
	/**
	 * 声明Log4j变量
	 */
	public static ResourceBundle resourceBundle = null;
	static Logger logger = Logger.getLogger(UserInfoMain.class.getName());
	
	UserInfoService us = new UserInfoServiceImpl();
	Map<String,Object> resultMap = new HashMap<String,Object>();
	
	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		String user_type = request.getParameter("user_type");
		String user_id = request.getParameter("user_id");
		int i = 0;
		try{
			if(user_type.equals("0")){
				UserInfo ui = setUserInfoBean(request);
				i = us.updateUserInfo(ui,new InsInfo(),Integer.parseInt(user_type),Integer.parseInt(user_id));
			}else if(user_type.equals("1")){
				InsInfo ii = setInsInfoBean(request);
				i = us.updateUserInfo(new UserInfo(),ii,Integer.parseInt(user_type),Integer.parseInt(user_id));
			}
			if(i>0){
				resultMap.put("result","OK");
			}else{
				resultMap.put("result","Failed");
				
			}
		}catch (Exception e) {
			resultMap.put("result","Error");
			logger.info(e);
		}
		ResponseToJson.responseOutWithJson(response,resultMap);
	}

	
	@SuppressWarnings("unchecked")
	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		Map<String, Object> map = new HashMap<String, Object>();
		int i = 0;
		request.setCharacterEncoding("utf-8");
		// 获得磁盘文件条目工厂。
		DiskFileItemFactory factory = new DiskFileItemFactory();
		String pathstr = "/upload/userprofile/";
		//上传文件的文件名
		String filename = "";
		// 获取文件上传需要保存的路径，pathstr自定义文件夹需存在文件夹需存在。
		String path = request.getSession().getServletContext().getRealPath(
				pathstr);

		// 设置暂时存放文件的存储室，这个存储室可以和最终存储文件的文件夹不同。因为当文件很大的话会占用过多内存所以设置存储室。
		factory.setRepository(new File(path));
		// 设置缓存的大小，当上传文件的容量超过缓存时，就放到暂时存储室。
		factory.setSizeThreshold(1024 * 1024);
		// 上传处理工具类
		ServletFileUpload upload = new ServletFileUpload(factory);

		// 调用 parseRequest（request）方法 获得上传文件 FileItem 的集合list 可实现多文件上传。
		List<FileItem> list;
		try {
			list = (List<FileItem>) upload.parseRequest(request);
			for (FileItem item : list) {

				// 如果获取的表单信息是普通的文本信息。即通过页面表单形式传递来的字符串。
				if (item.isFormField()) {
					// 获取表单属性名字。
					String textname = item.getFieldName();
					// 获取用户具体输入的字符串，
					String value = item.getString();
//					System.out.println(textname);
//					System.out.println(value);
					//将request传递过来的参数封装进map
					map.put(textname, value);
				}
				// 如果传入的是非简单字符串，而是图片，音频，视频等二进制文件。
				else {
					// 获取路径名
					String filepath = item.getName();
					// 取到最后一个反斜杠。
					int start = filepath.lastIndexOf("\\");
					// 截取上传文件的 字符串名字。+1是去掉反斜杠。
					filename = filepath.substring(start + 1);
					// 收到写到接收的文件中。
					OutputStream out = new FileOutputStream(new File(path,
							filename));
					InputStream in = item.getInputStream();

					int length = 0;
					byte[] buf = new byte[1024];
					logger.info("用户上传头像存放路径：" + path);
					logger.info("用户上传头像图片名称：" + filename);
					logger.info("获取文件总量的容量:" + item.getSize());
					while ((length = in.read(buf)) != -1) {
						out.write(buf, 0, length);
					}
					in.close();
					out.close();
				}
			}
			if("0".equals(map.get("user_type").toString())){
				UserInfo ui = new UserInfo();
				ui.setUserpic_path(pathstr+filename);
				i = us.updateUserInfo(ui,new InsInfo(),Integer.parseInt(map.get("user_type").toString()),Integer.parseInt(map.get("user_id").toString()));
			}else if("1".equals(map.get("user_type").toString())){
				InsInfo ii = new InsInfo();
				ii.setInspic_path(pathstr+filename);
				i = us.updateUserInfo(new UserInfo(),ii,Integer.parseInt(map.get("user_type").toString()),Integer.parseInt(map.get("user_id").toString()));
			}
			if(i>0){
				resultMap.put("result","OK");
			}else{
				resultMap.put("result","Failed");
				
			}
		} catch (FileUploadException e) {
			logger.info("文件上传失败！");
			resultMap.put("result", "Upload Failed");
			e.printStackTrace();
		}catch (FileNotFoundException e) {
			logger.info("未获取到图片列表！");
			resultMap.put("result", "no images");
			e.printStackTrace();
		}catch (Exception e) {
			logger.info("参数传递有误！");
			resultMap.put("result", "Error");
			e.printStackTrace();
		}
		
		ResponseToJson.responseOutWithJson(response, resultMap);
	}
	/**
	 * 将client传过来的参数封装成用户信息Bean
	 * @param request
	 * @return
	 */
	public UserInfo setUserInfoBean(HttpServletRequest request){
		UserInfo ui = new UserInfo();
		if(request.getParameter("username") != null && !"".equals(request.getParameter("username"))){
			ui.setUsername(Utils.convertString(request.getParameter("username")));
		}
		if(request.getParameter("msisdn") != null && !"".equals(request.getParameter("msisdn"))){
			ui.setMsisdn(request.getParameter("msisdn"));
		}
		if(request.getParameter("passwd") != null && !"".equals(request.getParameter("passwd"))){
			ui.setPasswd(Utils.encode(request.getParameter("passwd").getBytes()));
		}
		if(request.getParameter("address") != null && !"".equals(request.getParameter("address"))){
			ui.setAddress(Utils.convertString(request.getParameter("address")));
		}
		if(request.getParameter("sex") != null && !"".equals(request.getParameter("sex"))){
			ui.setSex(Integer.parseInt(request.getParameter("sex")));
		}
		return ui;
	}
	/**
	 * 将client传过来的参数封装成教练信息Bean
	 * @param request
	 * @return
	 */
	public InsInfo setInsInfoBean(HttpServletRequest request){
		InsInfo ii = new InsInfo();
		if(request.getParameter("ins_name") != null && !"".equals(request.getParameter("ins_name"))){
			ii.setIns_name(Utils.convertString(request.getParameter("ins_name")));
		}
		if(request.getParameter("ins_sex") != null && !"".equals(request.getParameter("ins_sex"))){
			ii.setIns_sex(Integer.parseInt(request.getParameter("ins_sex")));
		}
		if(request.getParameter("ins_addr") != null && !"".equals(request.getParameter("ins_addr"))){
			ii.setIns_addr(Utils.convertString(request.getParameter("ins_addr")));
		}
		if(request.getParameter("ins_age") != null && !"".equals(request.getParameter("ins_age"))){
			ii.setIns_age(Integer.parseInt(request.getParameter("ins_age")));
		}
		if(request.getParameter("ins_native_place") != null && !"".equals(request.getParameter("ins_native_place"))){
			ii.setIns_native_place(Utils.convertString(request.getParameter("ins_native_place")));
		}
		if(request.getParameter("ins_high") != null && !"".equals(request.getParameter("ins_high"))){
			ii.setIns_high(Integer.parseInt(request.getParameter("ins_high")));
		}
		if(request.getParameter("ins_weigh") != null && !"".equals(request.getParameter("ins_weigh"))){
			ii.setIns_weigh(Integer.parseInt(request.getParameter("ins_weigh")));
		}
		if(request.getParameter("st_id") != null && !"".equals(request.getParameter("st_id"))){
			ii.setSt_id(Integer.parseInt(request.getParameter("st_id")));
		}
		if(request.getParameter("history") != null && !"".equals(request.getParameter("history"))){
			ii.setHistory(Utils.convertString(request.getParameter("history")));
		}
		if(request.getParameter("teach_year") != null && !"".equals(request.getParameter("teach_year"))){
			ii.setTeach_year(Integer.parseInt(request.getParameter("teach_year")));
		}
		if(request.getParameter("teach_way") != null && !"".equals(request.getParameter("teach_way"))){
			ii.setTeach_way(Utils.convertString(request.getParameter("teach_way")));
		}
		if(request.getParameter("teach_pay") != null && !"".equals(request.getParameter("teach_pay"))){
			ii.setTeach_pay(Utils.convertString(request.getParameter("teach_pay")));
		}
		if(request.getParameter("ins_msisdn") != null && !"".equals(request.getParameter("ins_msisdn"))){
			ii.setIns_msisdn(request.getParameter("ins_msisdn"));
		}
		if(request.getParameter("ins_passwd") != null && !"".equals(request.getParameter("ins_passwd"))){
			ii.setIns_passwd(Utils.encode(request.getParameter("ins_passwd").getBytes()));
		}
		if(request.getParameter("ins_description") != null && !"".equals(request.getParameter("ins_description"))){
			ii.setIns_description(Utils.convertString(request.getParameter("ins_description")));
		}
		return ii;
	}

}
